/**
 * @description  交易所基础信息（债券指令）
 *
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col } from 'antd';
import { SecuritiesCodeC, InputNumberC, codeType, TradingMarketC } from '../../../../comps';
import moment from 'moment';
import style from './myStyle.less';
import FormItemLayout from './formItemLayout';

@Form.create()
class BondTransferC extends PureComponent {
  static defaultProps = {
    onRef: () => {},
  };
  constructor() {
    super();
    this.state = {
      SecuritiesCode: undefined, // 计算买入收益率和买入行权收益率用的证券代码相关数据
      price: undefined, // 净价
      date: moment().format('YYYYMMDD'), // 结算日期
      accruedInterest: undefined, // 应计利息
      orderQty: undefined, // 数量
      fullPrice: undefined, // 全价
      //   externalNameInfo: undefined          // 交易对手
    };
  }

  componentDidMount() {
    this.props.onRef(this);
  }
  //证券代码改变事件
  changePort = (e) => {
    console.log(e);
    const { price, orderQty } = this.state;
    const {
      form: { setFieldsValue },
      dispatch,
    } = this.props;
    if (e) {
      //证券代码变更时，重新设置交易市场，重新计算全价（因为应计利息要重新获取）、买入收益里、买入型全收益率和计算金额
      this.setState(
        {
          SecuritiesCode: e,
        },
        () => {
          this.getRate(); //获取行权收益率
        },
      );
      dispatch({
        type: 'bondTradeM/getInterest',
        payload: {
          secucode: e.secucode, // 根据证券代码获取应计利息
        },
        callback: (res) => {
          this.setState({
            accruedInterest: res.data.accruedInterest,
          });
          if (price !== undefined) {
            const nums = res.data.accruedInterest + price; // 全价=净价+应计利息
            setFieldsValue({
              fullPrice: nums,
              settlementAmount: orderQty !== undefined ? orderQty * nums : undefined,
            });
          } else {
            setFieldsValue({
              fullPrice: undefined,
              settlementAmount: undefined,
            });
          }
        },
      });
    } else {
      setFieldsValue({
        //条件不足时，全价、买入收益里、买入型全收益率和计算金额置空
        yield: undefined, // 清空买入收益率
        exerciseYield: undefined, // 清空行权买入收益率
        fullPrice: undefined,
        settlementAmount: undefined,
      });
      this.setState({
        accruedInterest: undefined,
      });
    }
    setFieldsValue({
      exchangecode: e ? `${e.exchangeCode == '101' ? '1' : e.exchangeCode == '113' ? 'B' : '2'}` : undefined,
    });
  };
  //获取行权收益率
  getRate = () => {
    const { SecuritiesCode, date, price } = this.state;
    const {
      dispatch,
      form: { setFieldsValue },
    } = this.props;
    if (SecuritiesCode && price && date) {
      let query = {
        //区分新增和回填时请求行权收益率的入参取值不同
        tradingcode: SecuritiesCode.tradingCode,
        exchangeCode: SecuritiesCode.exchangeCode,
        date,
        price,
        type: SecuritiesCode.exchangeCode == '101' ? 2 : SecuritiesCode.exchangeCode == '113' ? 1 : 3, //债券交易类型 银行间	银行间债券	1	上交所	上交所固收	2	 深交所	大宗现券	3
      };
      dispatch({
        type: 'bondTradeM/getRate',
        payload: {
          ...query,
        },
        callback: (res) => {
          const data = res.data;
          setFieldsValue({
            yield: data.yield !== null ? data.yield : undefined,
            exerciseYield: data.exerciseYield !== null ? data.exerciseYield : undefined,
          });
        },
      });
    } else {
      setFieldsValue({
        yield: undefined,
        exerciseYield: undefined,
      });
    }
  };
  // 净价改变事件
  changeprice = (e) => {
    const {
      form: { setFieldsValue },
    } = this.props;
    const { accruedInterest, orderQty } = this.state;
    // 净价变更时，重新计算全价、买入收益里、买入行权收益率和结算金额，
    if (e !== undefined && typeof e == 'number') {
      this.setState(
        {
          price: e,
        },
        () => {
          this.getRate(); //获取行权收益率
        },
      );
      if (accruedInterest !== undefined) {
        const num = e + accruedInterest; //全价
        setFieldsValue({
          fullPrice: num, // 赋值全价
          settlementAmount: orderQty !== undefined ? orderQty * num : undefined, // 结算金额=全价*数量；
        });
      } else {
        //条件不足时，全价、买入收益里、买入行权收益率和结算金额置空
        setFieldsValue({
          fullPrice: undefined, // 赋值全价
          settlementAmount: undefined,
        });
      }
    } else {
      setFieldsValue({
        //条件不足时，全价、买入收益里、买入行权收益率和结算金额置空
        yield: undefined, // 清空买入收益率
        exerciseYield: undefined, // 清空行权买入收益率
        fullPrice: undefined,
        settlementAmount: undefined,
      });
    }
  };
  // 数量改变事件
  changeorderQty = (e) => {
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.props;
    this.setState({
      orderQty: e,
    });
    if (e !== undefined && getFieldValue('fullPrice') !== undefined) {
      const num = e * getFieldValue('fullPrice'); // 结算金额=全价*数量；
      setFieldsValue({
        settlementAmount: num,
      });
    } else {
      setFieldsValue({
        settlementAmount: undefined,
      });
    }
  };
  // 表单内容
  formContent = () => {
    const {
      form: { getFieldValue },
    } = this.props;
    return (
      <>
        <Form>
          <Row className={style.mg5}>
            <Col span={24}>
              <SecuritiesCodeC // 证券代码
                title='证券代码'
                form={this.props.form}
                dataIndex='securityId'
                codeType={codeType.zq}
                onChange={(e) => {
                  this.changePort(e);
                  this.props.tradingCodeOnChange(e); //抛出证券代码
                }}
                extraLayout={FormItemLayout}
                rules={[{ required: true, message: '请选择证券代码!' }]}
              />
            </Col>
            <Col span={24}>
              <TradingMarketC // 交易市场
                title='交易市场'
                form={this.props.form}
                dataIndex='exchangecode'
                dataType={2}
                marketType={['jys', 'yhj']}
                rules={[{ required: true, message: '请选择交易市场!' }]}
                formItemLayout={FormItemLayout}
                disabled={true}
              />
            </Col>
            <Col span={24}>
              <InputNumberC
                title='数量'
                dataIndex='orderQty'
                placeholder='请输入'
                min={10}
                precision={0}
                splitStyle={true}
                form={this.props.form}
                formItemLayout={FormItemLayout}
                rules={[
                  { required: true, message: '请输入数量!' },
                  { pattern: /^[+-]?(\d){1,}0$/, message: '请输入10的倍数' },
                ]}
                onChange={this.changeorderQty}
                unit='张'
              />
            </Col>
            <Col span={24}>
              <InputNumberC
                title='净价'
                dataIndex='price'
                placeholder='请输入'
                precision={4}
                min={0.001}
                splitStyle={true}
                max={999999999999}
                form={this.props.form}
                formItemLayout={FormItemLayout}
                onChange={this.changeprice}
                rules={[{ required: getFieldValue('orderSide') == '4' ? false : true, message: `请输入净价` }]}
                unit='元'
              />
            </Col>
            <Col span={24}>
              <InputNumberC
                title='全价'
                dataIndex='fullPrice'
                placeholder='请输入'
                precision={4}
                splitStyle={true}
                min={0.001}
                max={999999999999}
                form={this.props.form}
                formItemLayout={FormItemLayout}
                disabled={true}
                rules={[{ required: true, message: `请输入全价` }]}
                unit='元'
              />
            </Col>
            <Col span={24}>
              <InputNumberC title='买入收益率' dataIndex='yield' form={this.props.form} formItemLayout={FormItemLayout} disabled={true} unit='%' precision={4} />
            </Col>
            <Col span={24}>
              <InputNumberC title='买入行权收益率' dataIndex='exerciseYield' form={this.props.form} formItemLayout={FormItemLayout} disabled={true} precision={4} unit='%' />
            </Col>
            <Col span={24}>
              <InputNumberC
                title='结算金额'
                dataIndex='settlementAmount'
                placeholder='请输入'
                min={0}
                precision={4}
                form={this.props.form}
                formItemLayout={FormItemLayout}
                disabled={true}
                splitStyle={true}
                rules={[{ required: true, message: `请输入金额` }]}
                unit='元'
              />
            </Col>
          </Row>
        </Form>
      </>
    );
  };

  // 获取校验并获取表单的值
  getInfo = () => {
    const {
      form: { validateFields },
    } = this.props;
    const { SecuritiesCode } = this.state;
    let query = undefined;
    validateFields((err, fieldsValue) => {
      if (!err) {
        query = fieldsValue;
        query.tradingcode = SecuritiesCode.secucode + '-' + query.securityId;
        // query.type=SecuritiesCode.exchangeCode=='101'?2:SecuritiesCode.exchangeCode=='113'?1:3//债券交易类型 银行间	银行间债券	1	上交所	上交所固收	2	 深交所	大宗现券	3
        delete query.securityId;
      }
    });
    return query;
  };

  render() {
    return <div>{this.formContent()}</div>;
  }
}

export default connect(({ bondTradeM }) => ({
  bondTradeM,
}))(BondTransferC);
